// Own header
#include "sensormodel.h"

/*!
  \class SensorModel
  \brief A model containing sensor types.
*/


/*!
  Constructor.
*/
SensorModel::SensorModel(QObject *parent) :
    QAbstractListModel(parent)
{
    QHash<int, QByteArray> roles;
    roles[TypeRole] = "type";
    setRoleNames(roles);
}


/*!
  Destructor.
*/
SensorModel::~SensorModel()
{
    clear();
}


/*!
  From QAbstractListModel.
*/
QVariant SensorModel::data(const QModelIndex &index,
                           int role /* = Qt::DisplayRole */) const
{
    const int itemIndex(index.row());

    if (!index.isValid() || itemIndex >= m_sensorTypes.count()) {
        // Invalid index!
        return QVariant();
    }

    QVariant value = QVariant();

    switch (role) {
        case TypeRole: {
            QString typeString(m_sensorTypes[itemIndex]);
            value = QVariant::fromValue(typeString);
            break;
        }
    }

    return value;
}


/*!
  From QAbstractListModel.
*/
int SensorModel::rowCount(const QModelIndex &parent) const
{
    Q_UNUSED(parent);
    return m_sensorTypes.count();
}


/*!
  From QAbstractListModel.
*/
void SensorModel::removeRow(int row, const QModelIndex &parent)
{
    Q_UNUSED(parent);

    if (0 > row && row > m_sensorTypes.count() - 1) {
        // Invalid row!
        return;
    }

    beginRemoveRows(QModelIndex(), row, row);
    m_sensorTypes.removeAt(row);
    endRemoveRows();
}


/*!
  Returns a byte array matching \a typeString if the model contains one.
*/
QByteArray SensorModel::typeByString(const QString &typeString)
{
    const int count(m_sensorTypes.count());
    QString temp;

    for (int i = 0; i < count; ++i) {
        temp = QString(m_sensorTypes[i]);

        if (!typeString.compare(temp)) {
            // The strings match!
            return m_sensorTypes[i];
        }
    }

    // Not found!
    return QByteArray();
}


/*!
  Sets \a type as the model content.
*/
void SensorModel::setSensorTypes(QList<QByteArray> types)
{
    if (types.count() == 0) {
        return;
    }

    beginInsertRows(QModelIndex(), 0, types.count() - 1);
    m_sensorTypes = types;
    endInsertRows();
    emit rowCountChanged(m_sensorTypes.count());
}


/*!
  Clears the model content.
*/
void SensorModel::clear()
{
    if (m_sensorTypes.count() == 0) {
        // Already empty!
        return;
    }

    beginRemoveRows(QModelIndex(), 0, m_sensorTypes.count() - 1);
    m_sensorTypes.clear();
    endRemoveRows();
    emit rowCountChanged(0);
}


// End of file.
